package com.win2014.bet888;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Hashtable;
import java.util.LinkedList;

import org.dom4j.DocumentHelper;
import org.jsoup.*; 
import org.jsoup.nodes.Document;  
import org.jsoup.nodes.Element;  
import org.jsoup.select.Elements;  

import com.win2014.Bean.OddsPdu;
import com.win2014.Bean.MatchPdu;
import com.win2014.DB.ConnectionPool.PooledConnection;
import com.win2014.DB.DBConnect;
import com.win2014.util.PUtils;

public class WinWithMixedGames {
	
	private Hashtable<String,OddsPdu> oddsTable = new Hashtable<String,OddsPdu>();
	private LinkedList<MatchPdu> Matches = new LinkedList<MatchPdu>();
	
	public static final int PROCESS_DATASYNC = 1;
	public static final int PROCESS_FHLPR = 2;
	
	
	public void processOdds(String date) {
		String addr = PUtils.loadProperties("MixedGamesOdds");
		//1388994009000
		if (date == null) {
			
		} else {
			addr += date;
		}
		
		addr += "&"+PUtils.currentMiles();
		
		System.out.println("odd address:"+addr);
		
		try {
			Document doc = Jsoup.connect(addr).timeout(200000).get();
		    Elements odds = doc.getElementsByTag("odds");
		    if (odds.size()>0) {
				Element odd = odds.get(0);
				Elements rowOdd = odd.getElementsByTag("i");
				
				for (Element i : rowOdd) {
					
					String oddsStr = i.text();
					if (oddsStr != null && !oddsStr.equals("")) {
						String[] oddsArray = oddsStr.split(",");
						OddsPdu pdu = new OddsPdu();
						pdu.setType1(oddsArray[0]);
						pdu.setType2(oddsArray[2]);
						pdu.setSerlNO(Integer.parseInt(oddsArray[1]));
						pdu.setB_host(Float.parseFloat(oddsArray[3]));
						pdu.setB_draw(Float.parseFloat(oddsArray[4]));
						pdu.setB_guest(Float.parseFloat(oddsArray[5]));
						pdu.setE_host(Float.parseFloat(oddsArray[6]));
						pdu.setE_draw(Float.parseFloat(oddsArray[7]));
						pdu.setE_guest(Float.parseFloat(oddsArray[8]));
						
						oddsTable.put(oddsArray[1], pdu);
						
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
	public String process(String date  , int pt){
		
		System.out.println("[**********************"+date+"***********************]");
		
		processOdds(date);
		
		String addr = PUtils.loadProperties("MixedGames");
		
		if (date == null) {
			
		} else {
			addr += date;
		}
		
		System.out.println("��ȡ���ݣ�"+addr);
		
		try {
			Document doc = Jsoup.connect(addr).timeout(200000).get();
			
			Element table = doc.getElementById("MatchTable");  
		    Elements rows = table.getElementsByTag("tr");
		    String time = "";
		    
		    for (Element element : rows) {
		    	String rowId = element.attr("id");
		    	String rowClass = element.attr("class");
		    	if (rowId.indexOf("tr_")!=0 && rowClass.indexOf("hunhe_")!=0) { //�������ص�Ͷע����Ͷע����ڵ�tr
		    		String timeRow = element.attr("class");
		    		
		    		if (timeRow.endsWith("niDate")) {//��ȡʱ��
		    			time = element.text();
						System.out.println(time);
					}  else if (rowId.indexOf("row_")==0) {
//						System.out.println(rowId);
						Elements coloms = element.getElementsByTag("td");
						
						MatchPdu match = new MatchPdu();
						
						Element col1 = coloms.get(0);//��һ�У����α��
						Element col2 = coloms.get(1);//�ڶ��У���������
						Element col3 = coloms.get(2);//�����У�ʱ��
//						System.out.println(col3.text());
						Element col4 = coloms.get(3);//�����У�״̬
						Element col5 = coloms.get(4);//�����У�����
						/**
						 * ��ȡ��������
						 */
						Elements tags = col5.getElementsByTag("span");
						for (Element font : tags) {
							String tagId = font.attr("id");
							if (tagId.indexOf("HomeOrder")>=0) {
//								System.out.println(font.text());
							}
						}
						
						Element col6 = coloms.get(5);//�����У�����
						Element col7 = coloms.get(6);//�����У��ȷ�
						String scorefull = col7.text();
						int hostSc = 0;
						int guestSc = 0;
						if (scorefull.indexOf("-")>=0 && scorefull.trim().length()>0) {
							System.out.println(scorefull);
							String[] scorefulls = scorefull.split("-");
							if (scorefulls.length > 1) {
								hostSc = Integer.parseInt(scorefulls[0]);
								guestSc = Integer.parseInt(scorefulls[1]);
							}
						}
						Element col8 = coloms.get(7);//�ڰ��У��Ͷ�
						/**
						 * ��ȡ�Ͷ�����
						 */
						tags = col8.getElementsByTag("span");
						for (Element font : tags) {
							String tagId = font.attr("id");
							if (tagId.indexOf("GuestOrder")>=0) {
//								System.out.println(font.text());
							}
						}
						
						Element col9 = coloms.get(8);//�ھ��У��볡�ȷ�
						
						System.out.println("-------------"+col5.text()+"VS"+col8.text()+"-------------");
						
						
						String serlNO = rowId.replaceAll("row_", "");
						
//						System.out.println(oddsTable.get(serlNO));
						
						

						Element col13 = coloms.get(12); //��ʮ���У�����
						Elements herfs = col13.getElementsByTag("a");
						for (Element herf : herfs) {
							if (herf.text().equals("��")) {
//								System.out.println(herf.text()+":"+herf.attr("href"));
								match.setAsianherf(herf.attr("href"));
							} else if (herf.text().equals("ŷ")) {
//								System.out.println(herf.text()+":"+herf.attr("href"));
								match.setEuroherf(herf.attr("href"));
							} else if (herf.text().equals("��")) {
//								System.out.println(herf.text()+":"+herf.attr("href"));
								match.setAnaherf(herf.attr("href"));
							} 
						}
						
						match.setMatchID(col1.text());
						match.setMatchSeriNO(Integer.parseInt(serlNO));
						match.setLeagueName(col2.text());
						match.setGameState(col4.text());
						match.setHostTeam(col5.text());
						String rt = col6.text();
						if (rt.indexOf("+")>=0) {
							rt = rt.substring(1);
						} else if (rt.trim().length()==0) {
							rt = "0";
						}
						match.setRscore(Integer.parseInt(rt));
						match.setHostScore(hostSc);
						match.setGuestScore(guestSc);
						match.setGuestTeam(col8.text());
						match.setHalfTimeScore(col9.text());
						match.setGameTime(col3.text());
						
						match.setMatchDay(time);
						
						Matches.add(match);
					}
		    		
				} else if (rowId.indexOf("tr_")==0) {
//					System.out.println("++++++++++++++++++++++++++++++++++++++++");
//					System.out.println(element);
					
					String matchSeri = rowId.replaceAll("tr_", "");
					
					OddsPdu pdu = oddsTable.get(matchSeri);
					
					if (pdu==null) {
						continue;
					}
					
					Elements tables = element.getElementsByTag("table");
					
					if (tables.size()>0) {
						Element oddTable = tables.get(0);
						Elements oddTr = oddTable.getElementsByTag("tr");
						for (Element hunhe : oddTr) {
							String hunheClass = hunhe.attr("class");
							if (hunheClass.equals("hunhe_1")) {
//								System.out.println("++++++++++++++++++����++++++++++++++++++++");
								Elements tds = hunhe.getElementsByTag("td");
								for (Element td : tds) {
									String tdid = td.attr("id");
									if (tdid.indexOf("cell_")>=0) {
										String title = "";
										String sp = "";
										Elements titles = td.getElementsByTag("b");
										Elements sps = td.getElementsByTag("span");
										title = titles.get(0).text();
										sp = sps.get(0).text();
//										System.out.println(title+"---->"+sp);
										pdu.setWinLostDrawNOthingValue(title, sp);
									}
								}
							} else if (hunheClass.equals("hunhe_2")) {
//								System.out.println("++++++++++++++++++�ȷ�++++++++++++++++++++");
								Elements tds = hunhe.getElementsByTag("td");
								for (Element td : tds) {
									String tdid = td.attr("id");
									if (tdid.indexOf("cell_")>=0) {
										String title = "";
										String sp = "";
										Elements titles = td.getElementsByTag("b");
										Elements sps = td.getElementsByTag("span");
										title = titles.get(0).text();
										sp = sps.get(0).text();
//										System.out.println(title+"---->"+sp);
										pdu.setPareScoreValue(title, sp);
									}
								}
							} else if (hunheClass.equals("hunhe_3")) {
//								System.out.println("++++++++++++++++++������++++++++++++++++++++");
								Elements tds = hunhe.getElementsByTag("td");
								for (Element td : tds) {
									String tdid = td.attr("id");
									if (tdid.indexOf("cell_")>=0) {
										String title = "";
										String sp = "";
										Elements titles = td.getElementsByTag("b");
										Elements sps = td.getElementsByTag("span");
										title = titles.get(0).text();
										sp = sps.get(0).text();
//										System.out.println(title+"---->"+sp);
										pdu.setScoreValue(title, sp);
									}
								}
							} else if (hunheClass.equals("hunhe_4")) {
//								System.out.println("++++++++++++++++++��ȫ��++++++++++++++++++++");
								Elements tds = hunhe.getElementsByTag("td");
								for (Element td : tds) {
									String tdid = td.attr("id");
									if (tdid.indexOf("cell_")>=0) {
										String title = "";
										String sp = "";
										Elements titles = td.getElementsByTag("b");
										Elements sps = td.getElementsByTag("span");
										title = titles.get(0).text();
										sp = sps.get(0).text();
//										System.out.println(title+"---->"+sp);
										pdu.setHalfFullValue(title, sp);
									}
								}
							} else if (hunheClass.equals("hunhe_5")) {
//								System.out.println("++++++++++++++++++ʤƽ��++++++++++++++++++++");
								Elements tds = hunhe.getElementsByTag("td");
								for (Element td : tds) {
									String tdid = td.attr("id");
									if (tdid.indexOf("cell_")>=0) {
										String title = "";
										String sp = "";
										Elements titles = td.getElementsByTag("b");
										Elements sps = td.getElementsByTag("span");
										title = titles.get(0).text();
										sp = sps.get(0).text();
//										System.out.println(title+"---->"+sp);
//										System.out.println(pdu);
										pdu.setWinLostDrawValue(title, sp);
									}
								}
							}
						}
					}
				}
			}
		    
		    if (pt == PROCESS_FHLPR) {
		    	
		    	org.dom4j.Document xmlDoc = DocumentHelper.createDocument();
				
		    	xmlDoc.setXMLEncoding("GBK");
				
		    	org.dom4j.Element rootElmt = xmlDoc.addElement("root_cel");
		    	
		    	org.dom4j.Element timeStamp = rootElmt.addElement("timeStamp");
		    	
		    	String docTime = "";
				
		    	for (int i = 0; i < Matches.size(); i++) {
			    	
			    	System.out.println("===============================");
			    	
			    	MatchPdu spdu = Matches.get(i);
			    	
			    	String day = spdu.getMatchDay().substring(0, 11);
			    	System.out.println("day��"+day);
			    	
			    	String matchId = spdu.getMatchID();
			    	System.out.println("matchId��"+matchId);
			    	
			    	String host = spdu.getHostTeam();
			    	String guest = spdu.getGuestTeam();
			    	System.out.println(host+" vs "+guest);
			    	
			    	OddsPdu opdu = oddsTable.get(""+spdu.getMatchSeriNO());
			    	
			    	float fhl = 0;
			    	
			    	if (opdu!=null) {
						
			    		if (spdu.getRscore() > 0) {
							if (opdu.getSp_spf_s() == 0) {
								System.out.println(opdu.getSp_rq_s()+","+opdu.getSp_rq_p()+","+opdu.getSp_rq_f()+",");
								fhl = 1.0f/(1.0f/opdu.getSp_rq_s() + 1.0f/opdu.getSp_rq_p() + 1.0f/opdu.getSp_rq_f()) ;
							} else {
								System.out.println(opdu.getSp_spf_f()+","+opdu.getSp_rq_s()+"");
								fhl = 1.0f/(1.0f/opdu.getSp_spf_f() + 1.0f/opdu.getSp_rq_s()) ;
							}
						} else if (spdu.getRscore() < 0) {
							if (opdu.getSp_spf_s() == 0) {
								System.out.println(opdu.getSp_rq_s()+","+opdu.getSp_rq_p()+","+opdu.getSp_rq_f()+",");
								fhl = 1.0f/(1.0f/opdu.getSp_rq_s() + 1.0f/opdu.getSp_rq_p() + 1.0f/opdu.getSp_rq_f()) ;
							} else {
								System.out.println(opdu.getSp_spf_s()+","+opdu.getSp_rq_f()+"");
								fhl = 1.0f/(1.0f/opdu.getSp_spf_s() + 1.0f/opdu.getSp_rq_f()) ;
							}
						} else if (spdu.getRscore() == 0) {
							if (opdu.getSp_spf_s() == 0) {
								System.out.println("0");
							} else {
								System.out.println(opdu.getSp_spf_s()+","+opdu.getSp_spf_p()+","+opdu.getSp_spf_f()+",");
								fhl = 1.0f/(1.0f/opdu.getSp_spf_s() + 1.0f/opdu.getSp_spf_p() + 1.0f/opdu.getSp_spf_f()) ;
							}
						} 
			    		System.out.println("�����ʣ�"+fhl);
			    		
					}
			    	
			    	org.dom4j.Element row ;
			    	
			    	if (docTime.equals("")) {
			    		timeStamp.addAttribute("time", day);
			    		row = timeStamp.addElement("row");
			    		docTime = day;
					} else {
						if (docTime.equals(day)) {
							row = timeStamp.addElement("row");
				    		docTime = day;
						} else {
							timeStamp = rootElmt.addElement("timeStamp");
							timeStamp.addAttribute("time", day);
				    		row = timeStamp.addElement("row");
				    		docTime = day;
						}
					}
			    	
			    	org.dom4j.Element mtid = row.addElement("matchId");mtid.setText(matchId);
			    	org.dom4j.Element mthost = row.addElement("host");mthost.setText(host);
			    	org.dom4j.Element mtGuest = row.addElement("guest");mtGuest.setText(guest);
			    	org.dom4j.Element mtfhl = row.addElement("fhl");mtfhl.setText(""+fhl);
			    	
			    	
			    }
		    	
		    	return xmlDoc.asXML();
		    	
			}
		    
		    
		    if (pt == PROCESS_DATASYNC) {
		    	
				
				for (int i = 0; i < Matches.size(); i++) {
					AsianOddsFetcher fetcher = new AsianOddsFetcher();
					MatchPdu spdu = Matches.get(i);
					fetcher.processAsianOdds(spdu.getMatchSeriNO(), spdu.getAsianherf());
					fetcher = null;
				}
			    
			    for (int i = 0; i < Matches.size(); i++) {
			    	PooledConnection conn = DBConnect.getConnection();
			    	conn.getConnection().setAutoCommit(false);
			    	MatchPdu spdu = Matches.get(i);
					spdu.setMatchDay(time);
					
					String sql = "insert into Win_BetGames (" +
							"matchSeriNO,leagueName," +
							"gameState,hostTeam," +
							"rscore,hostScore" +
							",guestScore,guestTeam," +
							"halfTimeScore,matchDay," +
							"gameTime,asianherf," +
							"euroherf,anaherf,matchID) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
					PreparedStatement pstmt = conn.getConnection().prepareStatement(sql); 
					pstmt.setInt(1, spdu.getMatchSeriNO());
					pstmt.setString(2, spdu.getLeagueName());
					pstmt.setString(3, spdu.getGameState());
					pstmt.setString(4, spdu.getHostTeam());
					pstmt.setInt(5, spdu.getRscore());
					pstmt.setInt(6, spdu.getHostScore());
					pstmt.setInt(7, spdu.getGuestScore());
					pstmt.setString(8, spdu.getGuestTeam());
					pstmt.setString(9, spdu.getHalfTimeScore());
//					Timestamp tm = new Timestamp(spdu.getMatchDayDate().getTime());
//					pstmt.setTimestamp(10, tm);
//					long sec = spdu.getMatchDayDate().getTime();
//					System.out.println("----->"+sec);
//					java.sql.Date dt = new Date(sec);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					pstmt.setString(10, sdf.format(spdu.getMatchDayDate()));
					pstmt.setString(11, spdu.getGameTime());
					pstmt.setString(12, spdu.getAsianherf());
					pstmt.setString(13, spdu.getEuroherf());
					pstmt.setString(14, spdu.getAnaherf());
					pstmt.setString(15, spdu.getMatchID());
					pstmt.execute();
					conn.getConnection().commit(); 
					conn.getConnection().setAutoCommit(true);
					conn.close();
					
					OddsPdu opdu = oddsTable.get(""+spdu.getMatchSeriNO());
					if (opdu!=null) {
						PooledConnection oddsConn = DBConnect.getConnection();
						oddsConn.getConnection().setAutoCommit(false);
						String oddSql = "insert into win_odds (" +
						"matchSeriNO," +
						"b_avrageEuroOdds_host,b_avrageEuroOdds_draw,b_avrageEuroOdds_guest," +
						"e_avrageEuroOdds_host,e_avrageEuroOdds_draw,e_avrageEuroOdds_guest," +
						"sp_spf_s,sp_spf_p,sp_spf_f," +
						"sp_rq_s,sp_rq_p,sp_rq_f," +
						"sp_jqs_0,sp_jqs_1,sp_jqs_2,sp_jqs_3,sp_jqs_4,sp_jqs_5,sp_jqs_6,sp_jqs_plus7," +
						"sp_score_10,sp_score_20,sp_score_21,sp_score_30,sp_score_31,sp_score_32,sp_score_40,sp_score_41," +
						"sp_score_42,sp_score_50,sp_score_51,sp_score_52,sp_score_winother," +
						"sp_score_00,sp_score_11,sp_score_22,sp_score_33,sp_score_drawother," +
						"sp_score_01,sp_score_02,sp_score_03,sp_score_12,sp_score_13,sp_score_23,sp_score_04,sp_score_14," +
						"sp_score_24,sp_score_05,sp_score_15,sp_score_25,sp_score_lostother," +
						"sp_ww,sp_wd,sp_wl,sp_dw,sp_dd,sp_dl,sp_lw,sp_ld,sp_ll) values " +
						"(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?" +
						",?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
						PreparedStatement oddsPstmt = oddsConn.getConnection().prepareStatement(oddSql);
						oddsPstmt.setInt(1, opdu.getSerlNO());
						oddsPstmt.setFloat(2, opdu.getB_host());
						oddsPstmt.setFloat(3, opdu.getB_draw());
						oddsPstmt.setFloat(4, opdu.getB_guest());
						oddsPstmt.setFloat(5, opdu.getE_host());
						oddsPstmt.setFloat(6, opdu.getE_draw());
						oddsPstmt.setFloat(7, opdu.getE_guest());
						oddsPstmt.setFloat(8, opdu.getSp_spf_s());
						oddsPstmt.setFloat(9, opdu.getSp_spf_p());
						oddsPstmt.setFloat(10, opdu.getSp_spf_f());
						oddsPstmt.setFloat(11, opdu.getSp_rq_s());
						oddsPstmt.setFloat(12, opdu.getSp_rq_p());
						oddsPstmt.setFloat(13, opdu.getSp_rq_f());
						oddsPstmt.setFloat(14, opdu.getSp_jqs_0());
						oddsPstmt.setFloat(15, opdu.getSp_jqs_1());
						oddsPstmt.setFloat(16, opdu.getSp_jqs_2());
						oddsPstmt.setFloat(17, opdu.getSp_jqs_3());
						oddsPstmt.setFloat(18, opdu.getSp_jqs_4());
						oddsPstmt.setFloat(19, opdu.getSp_jqs_5());
						oddsPstmt.setFloat(20, opdu.getSp_jqs_6());
						oddsPstmt.setFloat(21, opdu.getSp_jqs_plus7());
						
						oddsPstmt.setFloat(22,opdu.getSp_score_10());
						oddsPstmt.setFloat(23,opdu.getSp_score_20());
						oddsPstmt.setFloat(24,opdu.getSp_score_21());
						oddsPstmt.setFloat(25,opdu.getSp_score_30());
						oddsPstmt.setFloat(26,opdu.getSp_score_31());
						oddsPstmt.setFloat(27,opdu.getSp_score_32());
						oddsPstmt.setFloat(28,opdu.getSp_score_40());
						oddsPstmt.setFloat(29,opdu.getSp_score_41());
						oddsPstmt.setFloat(30,opdu.getSp_score_42());
						oddsPstmt.setFloat(31,opdu.getSp_score_50());
						oddsPstmt.setFloat(32,opdu.getSp_score_51());
						oddsPstmt.setFloat(33,opdu.getSp_score_52());
						oddsPstmt.setFloat(34,opdu.getSp_score_winother());
						oddsPstmt.setFloat(35,opdu.getSp_score_00());
						oddsPstmt.setFloat(36,opdu.getSp_score_11());
						oddsPstmt.setFloat(37,opdu.getSp_score_22());
						oddsPstmt.setFloat(38,opdu.getSp_score_33());
						oddsPstmt.setFloat(39,opdu.getSp_score_drawother());
						oddsPstmt.setFloat(40,opdu.getSp_score_01());
						oddsPstmt.setFloat(41,opdu.getSp_score_02());
						oddsPstmt.setFloat(42,opdu.getSp_score_03());
						oddsPstmt.setFloat(43,opdu.getSp_score_12());
						oddsPstmt.setFloat(44,opdu.getSp_score_13());
						oddsPstmt.setFloat(45,opdu.getSp_score_23());
						oddsPstmt.setFloat(46,opdu.getSp_score_04());
						oddsPstmt.setFloat(47,opdu.getSp_score_14());
						oddsPstmt.setFloat(48,opdu.getSp_score_24());
						oddsPstmt.setFloat(49,opdu.getSp_score_05());
						oddsPstmt.setFloat(50,opdu.getSp_score_15());
						oddsPstmt.setFloat(51,opdu.getSp_score_25());
						oddsPstmt.setFloat(52,opdu.getSp_score_lostother());
						oddsPstmt.setFloat(53,opdu.getSp_ww());
						oddsPstmt.setFloat(54,opdu.getSp_wd());
						oddsPstmt.setFloat(55,opdu.getSp_wl());
						oddsPstmt.setFloat(56,opdu.getSp_dw());
						oddsPstmt.setFloat(57,opdu.getSp_dd());
						oddsPstmt.setFloat(58,opdu.getSp_dl());
						oddsPstmt.setFloat(59,opdu.getSp_lw());
						oddsPstmt.setFloat(60,opdu.getSp_ld());
						oddsPstmt.setFloat(61,opdu.getSp_ll());

						oddsPstmt.execute();
						
						oddsConn.getConnection().commit(); 
						oddsConn.getConnection().setAutoCommit(true);
						
						oddsConn.close();
					}
			    
			    }
			}
		    
		    oddsTable = null;
		    Matches = null;
		    
		    System.gc();
		    
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}
	
	
}
